package com.qp.smsmarketing.utils;

import java.text.Normalizer;
import javax.swing.text.*;

public class JTextFieldFilter extends PlainDocument {

    public int maxLength;

    public static final String LOWERCASE  =
            "abcdefghijklmnopqrstuvwxyz";
    public static final String UPPERCASE  =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String ALPHA   =
            LOWERCASE + UPPERCASE;
    public static final String NUMERIC =
            "0123456789";
    public static final String FLOAT =
            NUMERIC + ".";
    public static final String ALPHA_NUMERIC =
            ALPHA + NUMERIC;

    protected String acceptedChars = null;
    protected boolean negativeAccepted = false;

    public JTextFieldFilter() {
        this(ALPHA_NUMERIC,30);
    }
    public JTextFieldFilter(String acceptedchars,int maxlen) {
        acceptedChars = acceptedchars;
        
        if (maxlen <= 0)  
            throw new IllegalArgumentException("You must specify a maximum length!");  
        maxLength = maxlen;
    }

    public void setNegativeAccepted(boolean negativeaccepted) {
        if (acceptedChars.equals(NUMERIC) ||
                acceptedChars.equals(FLOAT) ||
                acceptedChars.equals(ALPHA_NUMERIC)){
            negativeAccepted = negativeaccepted;
            acceptedChars += "-";
        }
    }

    @Override
    public void insertString
            (int offset, String  str, AttributeSet attr)
            throws BadLocationException {
        if (str == null || getLength() == maxLength) return;

        int totalLen = (getLength() + str.length());
//        if (totalLen <= maxLength)
//        {
//            super.insertString(offset, str, attr);
//            return;
//        }
//        String newStr = str.substring(0, (maxLength - getLength()));
//        super.insertString(offset, newStr, attr);

//        if (acceptedChars.equals(UPPERCASE))
//            str = str.toUpperCase();
//        else if (acceptedChars.equals(LOWERCASE))
//            str = str.toLowerCase();
//
//        for (int i=0; i < str.length(); i++) {
//            if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)
//                return;
//        }
//
//        if (acceptedChars.equals(FLOAT) ||
//                (acceptedChars.equals(FLOAT + "-") && negativeAccepted)) {
//            if (str.indexOf(".") != -1) {
//                if (getText(0, getLength()).indexOf(".") != -1) {
//                    return;
//                }
//            }
//        }
//
//        if (negativeAccepted && str.indexOf("-") != -1) {
//            if (str.indexOf("-") != 0 || offset != 0 ) {
//                return;
//            }
//        }
        
        str = Normalizer.normalize(str, Normalizer.Form.NFD);  
            str = str.replaceAll("[^\\p{ASCII}]", "");

        super.insertString(offset, str, attr);
    }
}
